//
//  JKComposeViewController.swift
//  JKWeibo
//
//  Created by albert on 16/6/25.
//  Copyright © 2016年 albert. All rights reserved.
//  发微博界面

import UIKit
import SVProgressHUD

class JKComposeViewController: UIViewController {

    // MARK: - 属性
    /** 发送按钮 */
    @IBOutlet weak var sendBtnItem: UIBarButtonItem!
    /** textView */
    @IBOutlet weak var textView: JKTextView!
    /** 工具条 */
    @IBOutlet weak var composeToolBar: UIToolbar!
    /** 工具条底部约束 */
    @IBOutlet weak var bottomToolBarCons: NSLayoutConstraint!
    /** 提示剩余可输入文字 */
    @IBOutlet weak var tipLabel: UILabel!
    /** 用户一共可以输入多少内容 */
    let maxCount = 140
    /** 容器视图的高度约束 */
    @IBOutlet weak var containerViewHeightCons: NSLayoutConstraint!
    /** 第三方键盘 */
    var keyboardView: UIView?
    
    /** 照片选择控制器 */
    var photoPickerVc: JKPhotoPickerCollectionViewController?
    
    /** 表情键盘控制器 */
    private lazy var emojiKeyboardVc: JKEmojiKeyboardViewController = JKEmojiKeyboardViewController { (emoticon) -> () in
        self.textView.insertEmoticon(emoticon)
        // 当插入表情时，主动调通textView的文字发生改变的函数
        self.textViewDidChange(self.textView)
    }
    
    // MARK: - 系统方法
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNav()
        
        addChildViewController(emojiKeyboardVc)
        
        containerViewHeightCons.constant = 0
    }
    
    /** 在viewWillAppear方法中调出键盘，执行工具条动画会有bug
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        textView.becomeFirstResponder()
    } */
    
    // 改为在viewDidAppear调出键盘
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if containerViewHeightCons.constant == 0 {
            textView.becomeFirstResponder()
            keyboardView = textView.inputView
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "photoPickerSegue" {
            photoPickerVc = segue.destinationViewController as? JKPhotoPickerCollectionViewController
            photoPickerVc?.didSelectPicBlock = {() -> Void in
                self.textViewDidChange(self.textView)
            }
            
            photoPickerVc?.didDeletePicBlock = {() -> Void in
                self.textViewDidChange(self.textView)
            }
        }
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 内部控制方法
    /** 初始化导航栏 */
    private func setupNav() {
        // 代码设置会显示不正确。why？
        //navigationItem.titleView = JKTitleView()
        sendBtnItem.enabled = false
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    /** 监听键盘frame */
    @objc private func keyboardWillChange(noti: NSNotification) {
        // 1.获取键盘的frame
        let rect = noti.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 2.计算要移动的距离
        let offsetY = JKScreenH - rect.origin.y
        bottomToolBarCons.constant = offsetY
        
        // 3.获取动画当前节奏，如果节奏是7，连续执行两次动画会直接忽略上一个，进入下一个动画
        let curve = noti.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        
        // 4.执行动画
        let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve.integerValue)!)
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - 各种按钮的点击
    /** 点击关闭 */
    @IBAction func closeBtnClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }

    /** 点击发送 */
    @IBAction func sendBtnClick(sender: UIButton) {
        
        // 1.获取用户输入内容
        let text = textView.getTextAndEmoticon()
        
        // 2.获取图片
        let image = photoPickerVc?.images.last
        
        JKNetworkingTool.sharedInstance.sendStatus(text, pic: image) { (dict, error) -> () in
            self.sendingStatus(error)
        }
    }
    
    /** 微博发送状态 */
    private func sendingStatus(error: NSError?) {
        
        // 退出键盘
        view.endEditing(true)
        
        SVProgressHUD.showWithStatus("发布中...")
        
        if error != nil {
            SVProgressHUD.showErrorWithStatus("发布微博失败！")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
            JKDispatchTool.after(JKTipDuration) { () -> Void in
                SVProgressHUD.dismiss()
            }
            return
        }
        
        SVProgressHUD.showSuccessWithStatus("发布微博成功！")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
        JKDispatchTool.after(JKTipDuration) { () -> Void in
            SVProgressHUD.dismiss()
        }
        
        self.closeBtnClick()
    }

    /** 点击键盘工具栏的图片按钮 */
    @IBAction func pictureBtnClick(sender: UIBarButtonItem) {
        
        // 退出键盘
        self.textView.resignFirstResponder()
        
        containerViewHeightCons.constant = JKScreenH * 0.7
        
        UIView.animateWithDuration(0.4) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    /** 点击键盘工具栏的表情按钮 */
    @IBAction func emojiBtnClick(sender: UIBarButtonItem) {
        // 通过观察得知，如果是系统默认键盘的时候，textView.inputView == nil
        // 是自定义键盘的时候，textView.inputView != nil
        
        // 注意点：要想切换键盘，必须先关闭键盘，切换之后再打开才有效
        
        // 关闭键盘
        textView.resignFirstResponder()
        
        // 判断是否为系统默认键盘
        if textView.inputView == emojiKeyboardVc.view { // 不是默认键盘
            textView.inputView = keyboardView
            
        }else { // 是默认键盘
            textView.inputView = emojiKeyboardVc.view
        }
        
        // 重新打开键盘
        textView.becomeFirstResponder()
    }
}

// MARK: - textView代理
extension JKComposeViewController: UITextViewDelegate {
    func scrollViewDidScroll(scrollView: UIScrollView) {
        view.endEditing(true)
        textView.inputView = nil
    }
    
    func textViewDidChange(textView: UITextView) {
        
        // 1.占位label是否显示
        self.textView.textChange()
        
        // 因为暂时还不会判断字符串中的中文字符和中文标点，所以两个英文字母算一个汉字，emoji算两个汉字之类的暂时没实现
        
        // 2.计算当前还可以输入多少内容
        // 2.1拿到用户已经输入了多少内容
        let currentCount = self.textView.getTextAndEmoticon().characters.count
        // 2.2当用户没有输入任何内容的时候隐藏提示label
        tipLabel.hidden = (currentCount == 0)
        // 2.3计算用户还可以输入多少内容
        let leftCount = maxCount - currentCount
        
        // 3.在tipLabel中显示当前剩余可以输入文字的个数
        tipLabel.text = "\(leftCount)"
        
        // 4.当textView有文字并且剩余可输入文字个数 >=0 的时候，发送按钮才可点击
        sendBtnItem.enabled = (textView.hasText() && (leftCount >= 0)) || (photoPickerVc?.images.count > 0)
        
        // 5.当剩余个数小于0的时候，则让tipLabel的文字变为红色
        tipLabel.textColor = (leftCount >= 0) ? UIColor.lightGrayColor() : UIColor.redColor()
    }
}
